#!/usr/bin/python  
#coding=utf-8  
import pexpect
import time
import sys
from time import sleep

#SSH连接成功时的命令行交互窗口中前面的提示字符的集合  
PROMPT = ['# ', '>>> ', '> ', '\$ ', 'password:']  

def send_command(child, cmd):
    # type: (pexpect.spawn, str) -> None
    """发送命令到子进程并等待响应
    
    Args:
        child (pexpect.spawn): SSH连接的子进程对象
        cmd (str): 要发送的命令
    
    Returns:
        None
    """
    #发送一条命令  
    child.sendline(cmd)  

    #期望有命令行提示字符出现  
    child.expect(PROMPT)  

    #将之前的内容都输出  
    print (child.before)  

def connect(user, host, password):
    # type: (str, str, str) -> pexpect.spawn
    """建立SSH连接
    
    Args:
        user (str): 用户名
        host (str): 主机地址
        password (str): 密码
    
    Returns:
        pexpect.spawn: SSH连接的子进程对象，连接失败时返回None
    """
    #表示主机已使用一个新的公钥的消息  
    ssh_newkey = 'Are you sure you want to continue connecting'  
    connStr = 'ssh -p 22 ' + user + '@' + host  

    #为ssh命令生成一个spawn类的对象  
    child = pexpect.spawn(connStr)  

    #期望有ssh_newkey字符、提示输入密码的字符出现，否则超时  
    ret = child.expect([pexpect.TIMEOUT,ssh_newkey,'[P|p]assword: '])  

    #匹配到超时TIMEOUT  
    if ret == 0:  
        print ('[-] Error Connecting'  )
        return  

    #匹配到ssh_newkey  
    if ret == 1:  
        #发送yes回应ssh_newkey并期望提示输入密码的字符出现  
        child.sendline('yes')  
        ret = child.expect([pexpect.TIMEOUT,'[P|p]assword: '])  

    #匹配到超时TIMEOUT  
    if ret == 0:  
        print ('[-] Error Connecting')  
        return  

    #发送passwd  
    child.sendline(password) 
    child.expect(PROMPT)
    
    print (connStr)
    return child


<<<main-function>>>
        

if __name__ == '__main__':
    main()